dataviz\figure\display/
winop.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
use minifb::{Key, MouseMode, Window, WindowOptions};
use resvg::{
    tiny_skia::{self, Pixmap},
    usvg::{self, fontdb},
};
use std::time::{Duration, Instant};

use super::hover::Hover;
use crate::figure::{canvas::pixelcanvas::PixelCanvas, drawers::drawer::Drawer, configuration::figureconfig::FigureConfig};

/// A utility struct for managing window operations and displaying graphics interactively.
pub struct Winop;

impl Winop {
    /// Creates a new `Winop` instance.
    ///
    /// # Returns
    /// A new `Winop` instance.
    pub fn new() -> Self {
        Self
    }

    /// Displays an SVG image in a window.
    ///
    /// # Parameters
    /// - `svg_content`: The SVG content as a string.
    /// - `window_title`: The title of the window.
    ///
    /// # Panics
    /// - If the SVG content cannot be parsed.
    /// - If the window cannot be created.
    pub fn display_svg(svg_content: &str, window_title: &str, figure_config: &FigureConfig) {
        // Initialize a font database.
        let mut fontdb = fontdb::Database::new();
        fontdb.load_system_fonts();
        fontdb.load_font_data(figure_config.font_label.clone().into_bytes());

        // Parse the SVG content.
        let mut opt = usvg::Options::default();
        opt.fontdb = fontdb.into();
        let tree = usvg::Tree::from_str(svg_content, &opt).expect("Failed to parse SVG");

        // Get the dimensions of the SVG from the view box.
        let size = tree.size();
        let width = size.width() as usize;
        let height = size.height() as usize;

        // Render the SVG into a pixmap.
        let mut pixmap = Pixmap::new(width as u32, height as u32).expect("Failed to create pixmap");
        resvg::render(&tree, tiny_skia::Transform::default(), &mut pixmap.as_mut());

        // Convert the pixmap into a pixel buffer.
        let buffer: Vec<u32> = pixmap
            .pixels()
            .iter()
            .map(|pixel| {
                let r = pixel.red();
                let g = pixel.green();
                let b = pixel.blue();
                let a = pixel.alpha();
                ((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32)
            })
            .collect();

        // Create a minifb window.
        let mut window = Window::new(
            window_title,
            width,
            height,
            WindowOptions {
                resize: false,
                scale: minifb::Scale::X1,
                ..WindowOptions::default()
            },
        )
        .expect("Unable to create window");

        // Display the image in the window.
        while window.is_open() && !window.is_key_down(Key::Escape) {
            window
                .update_with_buffer(&buffer, width, height)
                .expect("Failed to update buffer");
        }
    }

    /// Displays a plot in real-time with continuous updates.
    ///
    /// # Parameters
    /// - `canvas`: The `PixelCanvas` to draw on.
    /// - `plot`: The plot to be rendered, implementing `Hover` and `Drawer`.
    /// - `title`: The title of the window.
    /// - `update_data`: A closure to update the plot's data dynamically.
    /// - `fps`: Frames per second for rendering updates.
    ///
    /// # Panics
    /// - If the window cannot be created.
    pub fn display_real_time<T: Hover + Drawer>(
        canvas: &mut PixelCanvas,
        plot: &mut T,
        title: &str,
        mut update_data: impl FnMut(&mut T) + 'static,
        fps: u32,
    ) {
        let width = canvas.width as usize;
        let height = canvas.height as usize;

        let mut window = Window::new(
            title,
            width,
            height,
            WindowOptions {
                resize: true,
                scale: minifb::Scale::X1,
                ..WindowOptions::default()
            },
        )
        .unwrap_or_else(|e| panic!("Unable to open Window: {}", e));

        let frame_duration = Duration::from_secs_f32(1.0 / fps as f32);
        let mut last_frame_time = Instant::now();

        let mut hover_enabled = false;
        let mut show_hints = false;

        while window.is_open() && !window.is_key_pressed(Key::Escape, minifb::KeyRepeat::No) {
            // Update data for real-time rendering.
            if last_frame_time.elapsed() >= frame_duration {
                update_data(plot);
                plot.draw(canvas);
                last_frame_time = Instant::now();
            }

            // Render the canvas to a buffer.
            let mut buffer: Vec<u32> = Self::canvas_to_buffer(canvas);

            if hover_enabled {
                if let Some(mouse_pos) = window.get_mouse_pos(MouseMode::Pass) {
                    let (mouse_x, mouse_y) = (mouse_pos.0 as u32, mouse_pos.1 as u32);

                    if let Some(updated_buffer) = plot.handle_hover(mouse_x, mouse_y, canvas) {
                        buffer = updated_buffer;
                    }
                }
            }

            if show_hints {
                Self::render_hints(canvas);
            }

            if window.is_key_pressed(Key::C, minifb::KeyRepeat::No) {
                hover_enabled = !hover_enabled;
            }

            if window.is_key_pressed(Key::H, minifb::KeyRepeat::No) {
                show_hints = !show_hints;
            }

            window.update_with_buffer(&buffer, width, height).unwrap();
        }
    }

    /// Converts the canvas buffer into a format compatible with minifb.
    ///
    /// # Parameters
    /// - `canvas`: The `PixelCanvas` whose buffer needs conversion.
    ///
    /// # Returns
    /// A vector of `u32` representing the pixel data in ARGB format.
    fn canvas_to_buffer(canvas: &PixelCanvas) -> Vec<u32> {
        canvas
            .buffer
            .chunks_exact(3)
            .map(|rgb| {
                let r = rgb[0] as u32;
                let g = rgb[1] as u32;
                let b = rgb[2] as u32;
                (r << 16) | (g << 8) | b
            })
            .collect()
    }

    /// Displays a plot in an interactive window with hover functionality.
    ///
    /// # Parameters
    /// - `canvas`: The `PixelCanvas` to draw on.
    /// - `plot`: The plot to be rendered, implementing `Hover`.
    /// - `title`: The title of the window.
    ///
    /// # Panics
    /// - If the window cannot be created.
    pub fn display_interactive<T: Hover>(canvas: &mut PixelCanvas, plot: &T, title: &str) {
        let width = canvas.width as usize;
        let height = canvas.height as usize;

        let mut window = Window::new(
            title,
            width,
            height,
            WindowOptions {
                resize: true,
                scale: minifb::Scale::X1,
                ..WindowOptions::default()
            },
        )
        .unwrap_or_else(|e| panic!("Unable to open Window: {}", e));

        let mut hover_enabled = false;
        let mut show_hints = false;

        while window.is_open() && !window.is_key_pressed(Key::Escape, minifb::KeyRepeat::No) {
            // Render the canvas to a buffer.
            let mut buffer: Vec<u32> = Self::canvas_to_buffer(canvas);

            if show_hints {
                Self::render_hints(canvas);
            }

            if hover_enabled {
                if let Some(mouse_pos) = window.get_mouse_pos(MouseMode::Pass) {
                    let (mouse_x, mouse_y) = (mouse_pos.0 as u32, mouse_pos.1 as u32);

                    if let Some(updated_buffer) = plot.handle_hover(mouse_x, mouse_y, canvas) {
                        buffer = updated_buffer;
                    }
                }
            }

            if window.is_key_pressed(Key::H, minifb::KeyRepeat::No) {
                show_hints = !show_hints;
            }

            if window.is_key_pressed(Key::C, minifb::KeyRepeat::No) {
                hover_enabled = !hover_enabled;
            }

            window.update_with_buffer(&buffer, width, height).unwrap();
        }
    }

    /// Renders hints on the canvas for user guidance.
    ///
    /// # Parameters
    /// - `canvas`: The `PixelCanvas` to display hints on.
    ///
    /// # Note
    /// This function is a placeholder and needs to be implemented for specific hint rendering.
    fn render_hints(_canvas: &mut PixelCanvas) {
        // todo!();
    }
}